package com.ruihua.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruihua.mapper.ITIndexSettingPlus;
import com.ruihua.mapper.ITwoIndexPlus;
import com.ruihua.mapper.TIndexSettingMapper;
import com.ruihua.pojo.Result;
import com.ruihua.pojo.TIndexSetting;
import com.ruihua.pojo.TwoIndex;
import com.ruihua.service.ITIndexSettingService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.ruihua.utils.RedisConstants.Index_LEADERSHIP_KEY;
import static com.ruihua.utils.RedisConstants.Index_LEADERSHIP_TTL;
import static java.lang.Thread.sleep;

@Service
public class TIndexSettingServiceImpl implements ITIndexSettingService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private TIndexSettingMapper indexSettingMapper; // 一级指标mybatis
    @Resource
    private ITIndexSettingPlus indexSettingPlus; // 一级指标表
    @Resource
    private ITwoIndexPlus iTwoIndexPlus; // 二级指标表


    //查全部
    @Override
    public Result TIndexSettingAll() {
        System.out.println("这是孙git熟练使用记录，ui和原版都熟练使用");
        QueryWrapper<TIndexSetting> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 1);
        List<TIndexSetting> tIndexSettings = indexSettingPlus.selectList(queryWrapper);
        //判断数据是否为null或''
        if (tIndexSettings == null || tIndexSettings.isEmpty()) {
            return Result.error("没有数据");
        }
        return Result.ok(tIndexSettings);
    }

    //按年份查
    @Override
    public Result selectTIndexSetting(int year) {
        String Key = Index_LEADERSHIP_KEY + year;
        String index = stringRedisTemplate.opsForValue().get(Key);
        //Redis成功
        if (StrUtil.isNotBlank(index)) {
            List<TIndexSetting> tIndexSettings = JSONUtil.toList(index, TIndexSetting.class);
            return Result.ok(tIndexSettings);
        }
        //查数据库
        QueryWrapper<TIndexSetting> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("year", year)
                .eq("is_delete", 1);
        List<TIndexSetting> tIndexSettings = indexSettingPlus.selectList(queryWrapper);

        if (tIndexSettings == null || tIndexSettings.isEmpty()) {
            return Result.error("数据为空");
        }
        //通过序列化 存到Redis
        stringRedisTemplate.opsForValue().set(Key, JSONUtil.toJsonStr(tIndexSettings));
        //添加过期时间
        stringRedisTemplate.expire(Key, Index_LEADERSHIP_TTL, TimeUnit.MINUTES);
        return Result.ok(tIndexSettings);
    }

    //新增
    @Override
    public Result addITIndexSetting(TIndexSetting indexSetting) {
        // 获取当前年份
        String Key = Index_LEADERSHIP_KEY + (LocalDate.now().getYear());//大Key
        //判断二级指标唯一
        List<TIndexSetting> allTwoIndex = indexSettingMapper.getAllTwoIndex();
        //判重
        for (TIndexSetting twoIndex : allTwoIndex) {
            if (indexSetting.getLevelTwoIndex().equals(twoIndex.getLevelTwoIndex())) {
                return Result.error("存在重复的二级指标");
            }
        }
        //判断添加结果
        int i = -1;
        ValueOperations<String, String> opsedForValue = stringRedisTemplate.opsForValue();
        // 判断指定年份数据是否存在
        Boolean aBoolean = opsedForValue.getOperations().hasKey(Key);
        if (!aBoolean) {
            // 更新数据库
            i = indexSettingMapper.addITIndexSetting(indexSetting);
        } else {
            stringRedisTemplate.delete(Key);
            //更新数据库
            i = indexSettingMapper.addITIndexSetting(indexSetting);
            try {
                Thread.sleep(750); // 0.75秒，以毫秒为单位
            } catch (InterruptedException e) {
                // 处理中断异常
                e.printStackTrace();
            }
            stringRedisTemplate.delete(Key);
        }
        if (i > 0) {
            return Result.ok("添加成功");
        }
        return Result.error("添加失败");
    }

    //按id查
    @Override
    public Result getTIndexSetting(String id) {
        TIndexSetting tIndexSetting = indexSettingPlus.selectById(id);
        if (tIndexSetting != null) {
            return Result.ok(tIndexSetting);
        }
        return Result.error("查询失败");
    }

    //修改
    @Override
    public Result updateTIndexSetting(TIndexSetting tIndexSetting) {
        // 获取当前年份
        String Key = Index_LEADERSHIP_KEY + (LocalDate.now().getYear());//大Key
        stringRedisTemplate.delete(Key);
        //更新数据库
        int i = indexSettingMapper.updateTIndexSetting(tIndexSetting);
        try {
            Thread.sleep(750); // 0.75秒，以毫秒为单位
        } catch (InterruptedException e) {
            // 处理中断异常
            e.printStackTrace();
        }
        stringRedisTemplate.delete(Key);
        if (i > 0) {
            return Result.ok("修改成功");
        }
        return Result.error("修改失败");
    }

    //下发
    @Override
    @Transactional
    public Result issue(String issuingUnit, String id) {
        // 获取RedisKey
        String Key = Index_LEADERSHIP_KEY + (LocalDate.now().getYear());//因为业务,只可以下发本年
        //判断是否已下发
        TIndexSetting tIndexSetting = indexSettingPlus.selectById(id);
        String stateOfDelivery = tIndexSetting.getStateOfDelivery();
        if (stateOfDelivery.equals("已下发")) {
            return Result.error("指标已下发,不可重复下发");
        }
        stringRedisTemplate.delete(Key);
        int i = indexSettingMapper.issue(issuingUnit, id);
        try {
            Thread.sleep(750); // 0.75秒，以毫秒为单位
        } catch (InterruptedException e) {
            // 处理中断异常
            e.printStackTrace();
        }
        stringRedisTemplate.delete(Key);
        if (i > 0) {
            //同步添加二级表
            indexSettingMapper.addTwoIndex(tIndexSetting.getLevelOneIndex(), tIndexSetting.getLevelTwoIndex(),
                    tIndexSetting.getIssuingUnit());
            //删除二级表的Redis
            stringRedisTemplate.delete("部门台账");
            return Result.ok("下发成功");
        }
        return Result.error("下发失败");
    }

    @Override
    @Transactional
    public Result deleteIndex(String id) {
        //获取当前指标
        TIndexSetting tIndexSetting = indexSettingPlus.selectById(id);
        // 获取RedisKey
        String Key = Index_LEADERSHIP_KEY + (tIndexSetting.getYear());//大Key
        int i = -1;//删除结果
        //删除未下发
        if ("未下发".equals(tIndexSetting.getStateOfDelivery())) {
            stringRedisTemplate.delete(Key);
            //删除数据库
            i = indexSettingMapper.deleteIndex(id);
            try {
                Thread.sleep(750); // 0.75秒，以毫秒为单位
            } catch (InterruptedException e) {
                // 处理中断异常
                e.printStackTrace();
            }
            stringRedisTemplate.delete(Key);
        }
        if ("已下发".equals(tIndexSetting.getStateOfDelivery())) {
            String levelTwoIndex = tIndexSetting.getLevelTwoIndex();
            //获取下发给二级表的指标
            QueryWrapper<TwoIndex> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("secondaryindicator", levelTwoIndex);
            TwoIndex twoIndex = iTwoIndexPlus.selectOne(queryWrapper);
            //删除二级表的指标
            i = indexSettingMapper.deleteTwoIndex(twoIndex.getId());
            //删除二级表的Redis
            stringRedisTemplate.delete("部门台账");

            //修改一级表的下发状态
            // 构造修改条件
            UpdateWrapper<TIndexSetting> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", id);
            // 构造修改内容
            updateWrapper.set("state_of_delivery", "未下发"); // 设置要更新的字段及值
            //更新Redis
            stringRedisTemplate.delete(Key);
            // 调用 update 方法执行修改操作
            i = indexSettingPlus.update(null, updateWrapper);
            try {
                Thread.sleep(750); // 0.75秒，以毫秒为单位
            } catch (InterruptedException e) {
                // 处理中断异常
                e.printStackTrace();
            }
            stringRedisTemplate.delete(Key);
        }
        if (i > 0) {
            return Result.ok("删除成功");
        }
        return Result.error("删除失败");
    }

}
